import EvaluationSelect, {
  Value as EvaluationSelectValue,
} from '@/components/EvaluationSelect';
import FileUpload from '@/components/FileUpload';
import { eqV1ControllerCreate, eqV1ControllerShowOpen, eqV1ControllerUpdate, eqV1ControllerGetFiltersByTempEq } from '@/services/auto/eq';
import { evaluationV1ControllerShow } from '@/services/auto/evaluation';
import { ModalForm, ProForm } from '@ant-design/pro-components';
import { useRequest } from 'ahooks';
import { Alert, Button, Checkbox, Form, Input, message, Modal, Spin } from 'antd';
import { EQ_AUDIO_FILE_CLEAN_DAYS, EvaluationCategory, FileGroup } from 'common/utils/data';
import { find } from 'lodash';
import { PropsWithChildren, useContext, useEffect, useRef, useState } from 'react';
import AudioItem from './AudioItem';
import Filters from '@/components/Filters';
import { getId } from '@/utils';
import { FiltersValue } from '@/components/Filters/types';
import { useSearchParams } from '@umijs/max';
import { Context } from '@/pages/personal/mixer-huihifi/components/Provider';
import CreateFromUuidConfirm, { FormData as CreateFromUuidConfirmFormData } from './CreateFromUuidConfirm';
import UpdateAndKeepEQConfirm, { FormData as UpdateAndKeepEQConfirmFormData } from './UpdateAndKeepEQConfirm';

export interface FormData {
  name: string;
  current: EvaluationSelectValue<true>;
  presetFiles?: string[];
  files?: string[];
  filters?: FiltersValue;
  desc?: string;
}

interface Props {
  reload?: (uuid?: string) => void;
  data?: API.EQResult;
}

const PresetFiles = [
  {
    value: `${FileGroup.AUDIO_SYNTHESIS}/测试音乐1-流行音乐片段（较多低频）20241210.wav`,
    label: '测试音乐1-流行音乐片段（较多低频）.wav',
  },
  {
    value: `${FileGroup.AUDIO_SYNTHESIS}/测试音乐2-轻快的电影配乐.wav`,
    label: '测试音乐2-轻快的电影配乐.wav',
  },
];

export default (props: PropsWithChildren<Props>) => {
  const { reload, children, data } = props;

  const hidContext = useContext(Context);

  const [form] = Form.useForm<FormData>();
  const current = Form.useWatch('current', form);

  const tempFiltersRef = useRef<API.EQResultFilters[]>();

  const [createFromUuidConfirmForm] = Form.useForm<CreateFromUuidConfirmFormData>();
  const [updateAndKeepEQConfirmForm] = Form.useForm<UpdateAndKeepEQConfirmFormData>();

  const onSaveTypeRef = useRef<'onlySave' | 'saveAndSearch'>('onlySave');

  const [searchParams, setSearchParams] = useSearchParams();

  const setFormData = (data: API.EQResult) => {
    form.setFieldsValue({
      current: {
        evaluationUuid: data.evaluationUuid,
        dataGroup: data.dataGroup,
      },
      name: data.name,
      presetFiles: data.audioFiles.filter((i) =>
        PresetFiles.find((j) => i.includes(j.value)),
      ),
      files: data.audioFiles.filter(
        (i) => !PresetFiles.find((j) => i.includes(j.value)),
      ),
      desc: data.desc,
    });
  }

  const {
    loading: createFromLoading,
    runAsync: runAsyncCreateFrom,
    data: createFromData,
  } = useRequest(eqV1ControllerShowOpen, {
    manual: true,
    onSuccess: (res) => {
      if (!res) {
        message.warning('找不到该公开调音数据');
        return;
      }
      setFormData(res);
    }
  })

  // 请求频响数据
  const {
    data: evaluationData,
    loading: evaluationLoading,
    runAsync: runAsyncEvaluation,
    mutate: mutateEvaluation
  } = useRequest(
    () => evaluationV1ControllerShow({ uuid: current?.evaluationUuid! }),
    {
      manual: true,
    },
  );

  useEffect(() => {
    form.setFieldValue('filters', undefined);
    mutateEvaluation(undefined);
    if (current?.evaluationUuid) {
      runAsyncEvaluation();
    }
  }, [current?.evaluationUuid])

  useEffect(() => {
    if (!evaluationData || !current?.evaluationUuid || !current?.dataGroup) {
      return;
    }

    // 过滤出所选择的模式的频响数据
    const freqDbaDataList = find(
      evaluationData.datas,
      (i) => i.project.uuid === 'cdcf35b6-f37c-4b77-877f-9b8ddbf38c5b',
    );

    if (!freqDbaDataList) {
      return;
    }
    const freqDbaData = find(
      freqDbaDataList.children,
      (i) => i.group === current.dataGroup,
    );
    if (!freqDbaData) {
      return;
    }

    let filters: API.EQResultFilters[] | undefined = undefined;
    if(tempFiltersRef.current){
      filters = tempFiltersRef.current.slice();
      tempFiltersRef.current = undefined;
    }else{
      filters = (data ?? createFromData)?.filters;
    }

    filters = filters?.map(item => (
      { ...item, id: getId() }
    )) ?? []

    form.setFieldValue('filters', {
      freqToDB: freqDbaData,
      project: freqDbaDataList.project,
      eqs: filters,
      currentEQId: filters.length > 0 ? filters[0].id : undefined,
    });
  }, [evaluationData, current]);

  const [open, setOpen] = useState(false);

  const [copying, setCopying] = useState(false);

  useEffect(() => {
    const createFromUuid = searchParams.get('createFromUuid');
    if (!data && createFromUuid) {
      const deleteQuery = () => {
        searchParams.delete('createFromUuid');
        setSearchParams(searchParams);
      }
      Modal.confirm({
        title: '导入公开调音数据',
        content: <div className='mt-[16px]'>
          <CreateFromUuidConfirm form={createFromUuidConfirmForm} originalUuid={createFromUuid} />
        </div>,
        width: 800,
        onOk: () => {
          setCopying(true);
          return createFromUuidConfirmForm.validateFields().then((values) => {
            if (values.isOriginal) {
              return runAsyncCreateFrom({ uuid: createFromUuid }).then(() => {
                deleteQuery();
                setOpen(true);
              });
            } else {
              return runAsyncCreateFrom({
                uuid: createFromUuid,
                evaluationUuid: values.current.evaluationUuid,
                dataGroup: values.current.dataGroup
              }).then(() => {
                deleteQuery();
                setOpen(true);
              });
            }
          });
        },
        onCancel: () => {
          deleteQuery();
        }
      });
    }
  }, []);

  return (
    <ModalForm
      open={open}
      layout="horizontal"
      width={1366}
      labelCol={{ style: { width: 100 } }}
      modalProps={{
        maskClosable: false,
        cancelText: '退出',
        className: 'max-w-none',
      }}
      form={form}
      onOpenChange={(val) => {
        setOpen(val);
        if (val) {
          if (data && data.uuid) {
            setFormData(data);
          }
        } else {
          form.resetFields();
        }
      }}
      title={<div className='flex items-baseline'>
        {copying ? '导入公开调音数据' : data?.uuid ? '编辑AI调音定制' : '添加AI调音定制'}
        <span className='ml-[4px] text-xs text-red-500 font-normal'>
          如果调音无效，请使用最新的谷歌或Edge浏览器打开
        </span>
      </div>}
      trigger={children as JSX.Element}
      onFinish={(values) => {
        const { current, files, presetFiles, filters, name, desc } = values;

        const body = {
          name,
          desc,
          evaluationUuid: current.evaluationUuid!,
          dataGroup: current.dataGroup!,
          audioFiles: [...(files ?? []), ...(presetFiles ?? [])],
          filters: filters?.eqs.map(item => {
            const { id, ...restItem } = item;
            return restItem;
          }) || [],
        };

        const serviceRes = data?.uuid
          ? eqV1ControllerUpdate({ uuid: data.uuid }, body)
          : eqV1ControllerCreate(body);

        return serviceRes
          .then((v) => {
            message.success('操作成功');

            // 新增时，保存也直接关闭弹窗，但不打开相似耳机
            // 编辑时，仅保存不关闭弹窗
            // 新增，编辑时，点击确定，关闭弹窗，并打开相似耳机

            reload?.(
              onSaveTypeRef.current === 'saveAndSearch' && v
                ? v.uuid
                : undefined,
            );

            return !data?.uuid || onSaveTypeRef.current === 'saveAndSearch';
          })
          .catch(() => {
            return false;
          });
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [
            defaultDoms[0],
            <Button
              key="save"
              type="primary"
              onClick={() => {
                onSaveTypeRef.current = 'onlySave';
                props.submit();
              }}
            >
              保存
            </Button>,

            <Button
              key="saveAndSearch"
              type="primary"
              onClick={() => {
                onSaveTypeRef.current = 'saveAndSearch';
                props.submit();
              }}
            >
              保存并查找相似调音
            </Button>,

            ...(hidContext ? [
              <Button
                key="saveAndWrite"
                type="primary"
                onClick={() => {
                }}
              >
                保存并写入我的耳机
              </Button>,
            ] : [])
          ];
        },
      }}
    >
      <Spin spinning={createFromLoading}>
        <ProForm.Item
          name="current"
          label="当前耳机"
          required
          rules={[
            {
              validator: (_, value) => {
                return EvaluationSelect.getValidator(value, true, true);
              },
            },
          ]}
          extra={
            current ? (
              <>
                <Alert
                  className="mt-[8px]"
                  showIcon
                  type="warning"
                  message={<>
                    <span>请确保您的耳机配置与图片中一致</span>
                  </>}
                />
              </>
            ) : undefined
          }
        >
          <EvaluationSelect category={EvaluationCategory.EARBUDS} withDataGroup extraButtons={[
            <Button type="primary" ghost onClick={() => {
              Modal.confirm({
                title: '保留调音更换耳机',
                content: <div className='mt-[16px]'>
                  <UpdateAndKeepEQConfirm form={updateAndKeepEQConfirmForm} />
                </div>,
                width: 800,
                onOk: () => {
                  return updateAndKeepEQConfirmForm.validateFields().then((values) => {
                    const formValues = form.getFieldsValue();
                    return eqV1ControllerGetFiltersByTempEq({
                      beforeEvaluationUuid: formValues.current.evaluationUuid!,
                      beforeDataGroup: formValues.current.dataGroup!,
                      beforeFilters: formValues.filters?.eqs.map(item=>{
                        const { id, ...restItem } = item;
                        return restItem;
                      }) ?? [],
                      afterEvaluationUuid: values.current.evaluationUuid!,
                      afterDataGroup: values.current.dataGroup!,
                    }).then((res)=>{
                      tempFiltersRef.current = res.filters;
                      mutateEvaluation(undefined);
                      form.setFieldsValue({
                        current: values.current,
                      });
                    });
                  });
                },
              });
            }}>
              保留调音更换耳机
            </Button>
          ]} />
        </ProForm.Item>

        <ProForm.Item
          name="name"
          label="调音名称"
          required
          rules={[
            {
              required: true,
              message: '请输入 调音名称'
            },
          ]}
        >
          <Input maxLength={500} placeholder='选择耳机后自动填充，可二次修改' />
        </ProForm.Item>

        <ProForm.Item
          name="desc"
          label="描述"
        >
          <Input.TextArea showCount maxLength={500} placeholder='请输入描述，公开后可展示' autoSize={{ minRows: 3 }} />
        </ProForm.Item>

        <Spin spinning={evaluationLoading}>
          <ProForm.Item name="filters">
            <Filters />
          </ProForm.Item>
        </Spin>

        <div className='flex gap-[16px]'>
          <ProForm.Item label="试听音频" className="mb-0 flex-1 min-w-0">
            <ProForm.Item name="files" extra={<Alert className='mt-[4px]' showIcon message={`上传的试听音频将于${EQ_AUDIO_FILE_CLEAN_DAYS}天自动清理`} type="warning" />}>
              <FileUpload
                max={10}
                size={100}
                fileGroup={FileGroup.TEMP_EQ_AUDIO}
                ext={[
                  '.flac',
                  '.wav',
                  '.aiff',
                  '.mp3',
                  '.aifc',
                  '.au',
                  '.avr',
                  '.caf',
                  '.htk',
                  '.iff',
                  '.mat',
                  '.mpc',
                  '.ogg',
                  '.paf',
                  '.pcm',
                  '.pvf',
                  '.rf64',
                  '.sd2',
                  '.sds',
                  '.sf',
                  '.voc',
                  '.vox',
                  '.w64',
                  '.wve',
                  '.x',
                ]}
              />
            </ProForm.Item>

            <ProForm.Item
              name="presetFiles"
              label="预设音乐"
              extra="开源音乐来自：pixabay.com"
            >
              <Checkbox.Group options={PresetFiles} />
            </ProForm.Item>
          </ProForm.Item>
          <div className="w-[400px]" />
        </div>

        <ProForm.Item>
          <AudioItem></AudioItem>
        </ProForm.Item>
      </Spin>
    </ModalForm>
  );
};
